package com.kingbook.services;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.auth.LoginManager;
import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Master;
import com.kingbook.entity.Partner;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2019-12-18 21:37:35
 * @Version 1.0
 */
@Slf4j
@Service
public class PartnerService extends SupportService {

    @Autowired
    MasterService masterService;

    @PostConstruct
    private void init() {
        setNamespace("Partner");
    }

    @Transactional
    public JSONResult updatePartner(Map<String, Object> param) {
        int id = MapUtils.getIntValue(param, "id");
        int mid = MapUtils.getIntValue(param, "mid");
        int relatedMid = MapUtils.getIntValue(param, "relatedMid");
        String name = MapUtils.getString(param, "name");
        Partner partner = queryPartnerByName(mid, name);
        if (partner != null && partner.getId() != id && name.equals(partner.getName()))
            return JSONResult.failed(name + " 已添加");

        JSONResult result;
        if (id > 0) {
            if (relatedMid > 0) {
                JSONResult re = query(param);
                if (re.isSuccess() && re.getCount() > 0) {
                    JSONObject json = re.getData().getJSONObject(0);
                    int oldRelatedMid = json.getIntValue("relatedMid");
                    if(oldRelatedMid > 0) {
                        // 更换了关联伙伴，要检查是否有单，将原来的伙伴关系清楚
                        if (relatedMid != oldRelatedMid) {
                            int count = json.getIntValue("workspaceCount") + json.getIntValue("orderCount") + json.getIntValue("allotOrderCount") + json.getIntValue("allotToOrderCount");
                            if (count == 0) {     // 没有存在台班，如果是我主动添加的，可以删除
                                Map<String, Object> params = new HashMap<>(2);
                                params.put("mid", oldRelatedMid);
                                params.put("myRelatedMid", mid);
                                params.put("referralCode", 0);
                                params.put("relatedMid", 0);
                                modify(params);        //解除原来伙伴的关联关系
                            } else
                                return JSONResult.failed("该合作伙伴已经添加了你的台账，不能更换关系！");
                        }
                    }
                }
            }
            result = modify(param);
        } else
            result = save(param);
        if (relatedMid > 0) {
            // 对方存在我，就确立关联关系，否则主动添加一条
            Master master = masterService.getById(mid);
            Map<String, Object> params = Maps.newHashMap();
            params.put("mid", relatedMid);
            params.put("referralCode", master.getReferralCode());
            params.put("shortNumber", master.getShortNumber());
            params.put("phone1", master.getPhone1());
            params.put("phone2", master.getPhone2());
            params.put("phone3", master.getPhone3());
            Partner pp = findObject("queryRelatedPartner", params, Partner.class);
            if (pp != null) {
                params.put("id", pp.getId());
                params.put("name", master.getName());
                params.put("avatarUrl", master.getAvatarUrl());
                params.put("company", master.getCompany());
                params.put("address", master.getAddress());
                params.put("remarks", "对方主动关联认证");
                params.put("relatedMid", mid);
                modify(params);
            } else {
                insert("addRelatedPartner", param);
            }
        }
        return result;
    }

    public JSONResult updatePartnerByRelatedId(Map<String, Object> param) {
        int id = MapUtils.getIntValue(param, "id");
        param.put("myRelatedMid", id);
        param.remove("id");
        return modify(param);
    }

    public int getPartnerId(int mid, String name, boolean insert) {
        if (StringUtils.isNotEmpty(name)) {
            Map<String, Object> param = Maps.newHashMap();
            param.put("mid", mid);
            param.put("name", name);
            Partner partner = findObject("queryPartner", param, Partner.class);
            if (partner != null) {
                return partner.getId();
            } else if (insert) {
                JSONResult result = insertReturnKey("insert", param);
                return Integer.parseInt(result.getMsg());
            }
        }
        return 0;
    }

    public boolean isSystemPartner(int id, int mid) {
        Partner partner = findObject("queryPartner", putMap(id, mid), Partner.class);
        if (partner != null) {
            return partner.getRelatedMid() > 0;
        }
        return false;
    }

    private Partner queryPartnerByName(Integer mid, String name) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("mid", mid);
        param.put("name", name);
        return findObject("queryPartner", param, Partner.class);
    }

    public JSONResult queryPartnerAndWorkspace(Map<String, Object> param) {
        return query("queryPartnerAndWorkspace", param);
    }

    public JSONResult queryPartnerAndVehicle(Map<String, Object> param) {
        return query("queryPartnerAndVehicle", param);
    }

    public JSONResult find(int id, int mid) {
        JSONResult r = find("queryPartner", putMap(id, mid));
        if (r.isSuccess() && r.getCount() > 0) {
            JSONObject order = r.getData().getJSONObject(0);
            int relatedMid = order.getIntValue("relatedMid");
            JSONObject relatedMaster = new JSONObject();
            if (relatedMid > 0) {  //已确认的外派，查询出对应的工单
                JSONResult result = masterService.find(relatedMid);
                if (result.isSuccess() && result.getCount() > 0) {
                    relatedMaster = result.getData().getJSONObject(0);
                }
            }
            JSONArray array = new JSONArray();
            array.add(order);
            array.add(relatedMaster);
            r.setData(array);
        }
        return r;

    }
}
